﻿using System;
using System.Collections.ObjectModel;
using System.Windows;
using CustomerList.Model;
using GalaSoft.MvvmLight;
using GalaSoft.MvvmLight.Command;
using Microsoft.Phone.Tasks;
using MyMeetup.Entities;
using MyMeetup.Helpers;

namespace MyMeetup.ViewModels
{
    /// <summary>
    /// This class contains properties that a View can data bind to.
    /// <para>
    /// Use the <strong>mvvminpc</strong> snippet to add bindable properties to this ViewModel.
    /// </para>
    /// <para>
    /// You can also use Blend to data bind with the tool's support.
    /// </para>
    /// <para>
    /// See http://www.galasoft.ch/mvvm/getstarted
    /// </para>
    /// </summary>
    public class MainPageViewModel : ViewModelBase
    {

        INavigationService _navigationService = new NavigationService();

        public RelayCommand<Event> EventPageCommand { get; private set; }
        public RelayCommand<IGroup> GroupPageCommand { get; private set; }
        public RelayCommand LoadedCommand { get; private set; }

        public RelayCommand<Event> RsvpYesCommand { get; private set; }
        public RelayCommand<Event> RsvpNoCommand { get; private set; }
        public RelayCommand<Event> CheckinCommand { get; private set; }

        public RelayCommand EmailMeCommand { get; private set; } 
        public RelayCommand SearchClick { get; private set; }
        public RelayCommand SettingsClick { get; private set; }
        public RelayCommand LogoutClick { get; private set; }
        public RelayCommand LogInClick { get; private set; }

        public RelayCommand<Member> UserClick { get; private set; }


        public string ApplicationTitle
        {
            get { return "my meetup"; }
        }

        public string PageName
        {
            get { return ""; }
        }


        private string _userId;

        private DataService _dataService;

        /// <summary>
        /// Initializes a new instance of the MainPageViewModel class.
        /// </summary>
        public MainPageViewModel()
        {
            _dataService = new DataService();
            LoadedCommand = new RelayCommand(LoadPage);
            EventPageCommand = new RelayCommand<Event>(GoToEventPage);
            GroupPageCommand = new RelayCommand<IGroup>(GoToGroupPage);
            LogoutClick = new RelayCommand(Logout);
            LogInClick = new RelayCommand(Login);
            UserClick = new RelayCommand<Member>(GoToUser);
            SearchClick = new RelayCommand(GoToSearch);
            SettingsClick = new RelayCommand(GoToSettings);
            RsvpYesCommand = new RelayCommand<Event>(SubmitRsvpYes);
            RsvpNoCommand = new RelayCommand<Event>(SubmitRsvpNo);
            CheckinCommand = new RelayCommand<Event>(CheckinToEvent);
            EmailMeCommand = new RelayCommand(EmailMe);

            

            ////if (IsInDesignMode)
            ////{
            ////    // Code runs in Blend --> create design time data.
            ////}
            ////else
            ////{
            ////    // Code runs "for real": Connect to service, etc...
            ////}
        }

        private void GoToSearch()
        {
            _navigationService.NavigateTo(new Uri("/SearchPage.xaml", UriKind.Relative));
        }

        private void GoToSettings()
        {
            _navigationService.NavigateTo(new Uri("/MySettings.xaml", UriKind.Relative));
        }

        private void GoToEventPage(Event selectedEvent)
        {
            _navigationService.NavigateTo(new Uri("/EventPage.xaml", UriKind.Relative));   
        }

        private void GoToGroupPage(IGroup selectedGroup)
        {
            _navigationService.NavigateTo(new Uri("/PanoramaGroupPage.xaml", UriKind.Relative));
        }


        private void LoadPage()
        {
            if(App.Settings.FirstRun)
            {
                App.Settings.FirstRun = false;
                var ph = new PrivacyHelper();
                ph.Show();
            }

            if (!App.Settings.IsAuthenticated)
            {
                _navigationService.NavigateTo(new Uri("/LoginPage.xaml", UriKind.Relative));
                return;
            }

            CurrentUser = App.Settings.AuthUser;

            GetLoggedOnUser();
            LoadNews();
            LoadGroups();
            LoadEvents();
            var rand = new RandomMessage();
            AboutText = "Developed " + rand.NextMessage() + ", by Stephen Enloe";
        }

        private void CheckinToEvent(Event selectedEvent)
        {
            var checkinHelper = new CheckinHelper(_dataService, _navigationService);
            checkinHelper.CheckinToEvent(selectedEvent.id);
        }


        private void SubmitRsvpYes(Event selectedEvent)
        {
            SubmitRsvp(selectedEvent, RSVPType.Yes);
        }

        private void SubmitRsvpNo(Event selectedEvent)
        {
            SubmitRsvp(selectedEvent, RSVPType.No);
        }

        private void SubmitRsvp(Event selectedEvent, RSVPType response)
        {
            var rsvpHelper = new RsvpHelper(_dataService, _navigationService);
            rsvpHelper.SubmitRsvp(selectedEvent.id, response, (rsvpResponse)=> selectedEvent.self.rsvp.response = rsvpResponse.response);
        }


        private void GetLoggedOnUser()
        {
            _dataService.GetMember((x) =>
                                       {
                                           CurrentUser = x;
                                       }, ResponseHelper.ErrorCallback);
        }

        private void LoadNews()
        {
            _dataService.GetNews(CurrentUser.MemberId, (x) =>
                                                               {
                                                                   LatestNews = x;
                                                               }, ResponseHelper.ErrorCallback);

        }


        void LoadGroups()
        {
            _dataService.GetGroups(CurrentUser.MemberId, (x) =>
                                                                 {
                                                                     UserGroups = x;
                                                                 }, ResponseHelper.ErrorCallback);
        }


        private void LoadEvents()
        {
            _dataService.GetEventsForUser(CurrentUser.MemberId, (x) =>
                                                                        {
                                                                            UpcomingEvents = x;
                                                                        }, ResponseHelper.ErrorCallback);
        }

        public void GoToUser(Member member)
        {
            //_navigationService.NavigateTo(new Uri("/MemberPage.xaml?memberId=" + App.Settings.AuthUser.Id, UriKind.Relative));
        }



        private void EmailMe()
        {
            var emailComposeTask = new EmailComposeTask();

            emailComposeTask.Subject = "MyMeetup";
            emailComposeTask.Body = "";
            emailComposeTask.To = "senloe-wp7@hotmail.com";
            
            emailComposeTask.Show();
        }

        private void Logout()
        {
            App.Settings.Logout();
//            LatestNews = null;
            _navigationService.NavigateTo(new Uri("/LoginPage.xaml", UriKind.Relative));
        }

        private void Login()
        {
            _navigationService.NavigateTo(new Uri("/LoginPage.xaml", UriKind.Relative));
        }


        public override void Cleanup()
        {
            // Clean own resources if needed

            base.Cleanup();
        }

        public Visibility IsLoggedInVisibility
        {
            get { return App.Settings.IsAuthenticated ? Visibility.Visible : Visibility.Collapsed; }
        }

        public Visibility ShowLoginVisibility
        {
            get { return App.Settings.IsAuthenticated ? Visibility.Collapsed : Visibility.Visible; }
        }


        /// <summary>
        /// The <see cref="AboutText" /> property's name.
        /// </summary>
        public const string AboutTextPropertyName = "AboutText";

        private string _aboutText = "";

        /// <summary>
        /// Gets the AboutText property.
        /// TODO Update documentation:
        /// Changes to that property's value raise the PropertyChanged event. 
        /// This property's value is broadcasted by the Messenger's default instance when it changes.
        /// </summary>
        public string AboutText
        {
            get
            {
                return _aboutText;
            }

            set
            {
                if (_aboutText == value)
                {
                    return;
                }

                _aboutText = value;

                // Update bindings, no broadcast
                RaisePropertyChanged(AboutTextPropertyName);
            }
        }

        /// <summary>
        /// The <see cref="CurrentUser" /> property's name.
        /// </summary>
        public const string CurrentUserPropertyName = "CurrentUser";

        private Member _currentUser;

        /// <summary>
        /// Gets the CurrentUser property.
        /// TODO Update documentation:
        /// Changes to that property's value raise the PropertyChanged event. 
        /// This property's value is broadcasted by the Messenger's default instance when it changes.
        /// </summary>
        public Member CurrentUser
        {
            get
            {
                return _currentUser;
            }

            set
            {
                if (_currentUser == value)
                {
                    return;
                }

                var oldValue = _currentUser;
                _currentUser = value;


                // Update bindings, no broadcast
                RaisePropertyChanged(CurrentUserPropertyName);
            }
        }


        /// <summary>
        /// The <see cref="SelectedGroup" /> property's name.
        /// </summary>
        public const string SelectedGroupPropertyName = "SelectedGroup";

        private IGroup _selectedGroup;

        /// <summary>
        /// Gets the SelectedGroup property.
        /// TODO Update documentation:
        /// Changes to that property's value raise the PropertyChanged event. 
        /// This property's value is broadcasted by the Messenger's default instance when it changes.
        /// </summary>
        public IGroup SelectedGroup
        {
            get
            {
                return _selectedGroup;
            }

            set
            {
                if (_selectedGroup == value)
                {
                    return;
                }

                var oldValue = _selectedGroup;
                _selectedGroup = value;


                // Update bindings and broadcast change using GalaSoft.MvvmLight.Messenging
                RaisePropertyChanged(SelectedGroupPropertyName, oldValue, value, true);
            }
        }


        /// <summary>
        /// The <see cref="SelectedEvent" /> property's name.
        /// </summary>
        public const string SelectedEventPropertyName = "SelectedEvent";

        private Event _selectedEvent;

        /// <summary>
        /// Gets the SelectedEvent property.
        /// TODO Update documentation:
        /// Changes to that property's value raise the PropertyChanged event. 
        /// This property's value is broadcasted by the Messenger's default instance when it changes.
        /// </summary>
        public Event SelectedEvent
        {
            get
            {
                return _selectedEvent;
            }

            set
            {
                if (_selectedEvent == value)
                {
                    return;
                }

                var oldValue = _selectedEvent;
                _selectedEvent = value;

                // Update bindings and broadcast change using GalaSoft.MvvmLight.Messenging
                RaisePropertyChanged(SelectedEventPropertyName, oldValue, value, true);
            }
        }



        /// <summary>
        /// The <see cref="LatestNews" /> property's name.
        /// </summary>
        public const string LatestNewsPropertyName = "LatestNews";

        private ObservableCollection<Activity> _latestNews = new ObservableCollection<Activity>();

        /// <summary>
        /// Gets the LatestNews property.
        /// TODO Update documentation:
        /// Changes to that property's value raise the PropertyChanged event. 
        /// This property's value is broadcasted by the Messenger's default instance when it changes.
        /// </summary>
        public ObservableCollection<Activity> LatestNews
        {
            get
            {
                return _latestNews;
            }

            set
            {
                if (_latestNews == value)
                {
                    return;
                }

                var oldValue = _latestNews;
                _latestNews = value;

                // Update bindings, no broadcast
                RaisePropertyChanged(LatestNewsPropertyName);
            }
        }


        /// <summary>
        /// The <see cref="UserGroups" /> property's name.
        /// </summary>
        public const string UserGroupsPropertyName = "UserGroups";

        private ObservableCollection<IGroup> _userGroups = new ObservableCollection<IGroup>();

        /// <summary>
        /// Gets the UserGroups property.
        /// TODO Update documentation:
        /// Changes to that property's value raise the PropertyChanged event. 
        /// This property's value is broadcasted by the Messenger's default instance when it changes.
        /// </summary>
        public ObservableCollection<IGroup> UserGroups
        {
            get
            {
                return _userGroups;
            }

            set
            {
                if (_userGroups == value)
                {
                    return;
                }

                var oldValue = _userGroups;
                _userGroups = value;

                // Update bindings, no broadcast
                RaisePropertyChanged(UserGroupsPropertyName);

            }
        }

        /// <summary>
        /// The <see cref="UpcomingEvents" /> property's name.
        /// </summary>
        public const string UpcomingEventsPropertyName = "UpcomingEvents";

        private ObservableCollection<Event> _upcomingEvents = new ObservableCollection<Event>();

        /// <summary>
        /// Gets the UpcomingEvents property.
        /// TODO Update documentation:
        /// Changes to that property's value raise the PropertyChanged event. 
        /// This property's value is broadcasted by the Messenger's default instance when it changes.
        /// </summary>
        public ObservableCollection<Event> UpcomingEvents
        {
            get
            {
                return _upcomingEvents;
            }

            set
            {
                if (_upcomingEvents == value)
                {
                    return;
                }

                var oldValue = _upcomingEvents;
                _upcomingEvents = value;

                // Update bindings, no broadcast
                RaisePropertyChanged(UpcomingEventsPropertyName);
            }
        }

    }
}